<template>
  <div class="app-container">
    <p class="title">添加/修改角色</p>
    <el-form label-width="100px">
      <el-form-item label="角色名称">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="角色code">
        <el-input v-model="formData.code" />
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="formData.description" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="loading" @click="onSubmit"
          >提交</el-button
        >
        <el-button>重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getInfo, add, edit } from '@/api/role'

export default {
  name: 'AddEditRole',
  data() {
    return {
      type: 'add',
      formData: {
        name: '',
        code: '',
        description: ''
      },
      loading: false
    }
  },
  created() {
    const id = this.$route.params.id
    if (id) {
      this.type = 'edit'
      this.id = id
      getInfo(id).then(res => {
        this.formData = res.data
      })
    }
  },
  methods: {
    onSubmit() {
      this.loading = true
      let requestPromise
      const params = { ...this.formData }
      if (this.type === 'edit') {
        params.id = this.id
        requestPromise = edit(params)
      } else {
        requestPromise = add(params)
      }
      requestPromise
        .then(res => {
          if (res.code === 200) {
            this.$message.success('操作成功')
            this.$router.push('/auth/role')
          }
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.title {
  font-size: 24px;
  font-weight: bold;
}
.el-input {
  width: 180px;
}
</style>
